package com.rebate.web.filter;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

public class LoginFilter implements Filter {
	
	private Pattern exceptUrlRegx;
	
	private String redirectUrl;
	
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		Object user = session.getAttribute("user");
		System.out.println("请求路径:"+req.getServletPath());
		if ((user == null)) {
			if (exceptUrlRegx.matcher(req.getServletPath()).matches()) {
				chain.doFilter(request, response);
			}else {
				session.invalidate();
				resp.sendRedirect(req.getContextPath()+redirectUrl);
			}
		} else {
			chain.doFilter(request, response);
		}
		
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String regex = filterConfig.getInitParameter("exceptUrlRegx");
		redirectUrl = filterConfig.getInitParameter("redirectUrl");
		if (!StringUtils.isBlank(regex)) {
			exceptUrlRegx = Pattern.compile(regex);
		}
	}

	@Override
	public void destroy() {}
}
